package com.nulldev.util.web.nTubeExtensions.Redwood.pages;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.CachedItem;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.YouTubeExtractor;
import com.nulldev.util.web.nTube.resources.project_redwood.RedwoodResource;
import com.nulldev.util.web.nTubeExtensions.Redwood.Redwood;

@Deprecated
public class RedwoodEmbedFile extends HttpPage3 {

	public RedwoodEmbedFile() {
		super("/resources/redwood/youtube_embed.js");
		this.setCachingMethod(CachingMethod.SHORT_CACHE);
	}

	private static final CachedItem<String> embed = new CachedItem<String>("YTE_REDWOOD_EMBED", Long.MAX_VALUE) {

		@Override
		public String accquire() throws Exception {
			YouTubeExtractor.extractor.waitFor();
			Redwood.player.waitFor();
			return HttpClient.getString().url(Redwood.player_url.get().replace("base.js", "embed.js")).create().dataThenClose();
		}
	};

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		if (!Redwood.ENABLE_AUTO_UPDATING)
			return new Response(200, FileUtil.getResourceStream(RedwoodResource.class, "youtube_embed.js")).setCustomMime("application/javascript");
		try {
			return new Response(200, createStream(embed.getAuto())).setCustomMime("application/javascript");
		} catch (Exception e) {
			JVM.errorln(e);
			return new Response(503);
		}
	}

}
